const { src, dest, task, series, watch, parallel } = require('gulp');
const uglify = require('gulp-uglify-es').default;
const rename = require('gulp-rename');
const less = require('gulp-less');
const minifycss = require('gulp-minify-css');
const imgmin = require('gulp-imagemin');
const cache = require('gulp-cache');
const minifyHtml = require('gulp-minify-html');
const extender = require('gulp-html-extend');
const del = require('del');
const connect = require('gulp-connect')

//处理lib文件
task('lib', function () {
  return (
    src('./src/lib/**/*.*')
      .pipe(dest('dist/lib'))
      .pipe(connect.reload())
  )
})

//处理js
task('js', function () {
  return (
    src('./src/js/*.js')
      .pipe(dest('./dist/js'))
      .pipe(uglify())
      .pipe(
        rename({
          suffix: '.min'
        })
      )
      .pipe(dest('./dist/js'))
      .pipe(connect.reload())
  )
})

//处理 less文件
task('less', function () {
  return (
    src('./src/less/*.less')
      .pipe(less())
      .pipe(dest('./dist/css'))
      .pipe(minifycss())
      .pipe(
        rename({
          suffix: '.min'
        })
      )
      .pipe(dest('./dist/css'))
      .pipe(connect.reload())
  )
})

// 处理图片
task('img', function () {
  return (
    src('./src/images/*.*')
    // .pipe(cache(imgmin()))
    .pipe(dest('./dist/images'))
    .pipe(connect.reload())
  )
})

//处理html
task('html', function () {
  return (
    src('./src/*.html')
    .pipe(extender())
    .pipe(minifyHtml())
    .pipe(dest('./dist'))
    .pipe(connect.reload())
  )
})

//清除dist
task('clean', function (){
  return del('./dist')
})

//监听任务
task('watch', function () {
  watch('./src/**/*.html', series('html'))
  watch('./src/less/*.less', series('less'))
  watch('./src/js/*.js', series('js'))
  watch('./src/lib/**/*.*', series('lib'))
  watch('./src/img/*.*', series('img'))
})

//定义任务
task('connect', function () {
  return (
    connect.server({
      root: './dist',
      livereload: true,
      port: 9999
    })
  )
})

//series可以组合多个任务
task(
  'default',
  series(
    'clean',
    'html',
    'less',
    'js',
    'img',
    'lib',
    parallel('watch', 'connect')
  )
)